package com.senlingspace.web.controller.common;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Stopwatch;
import com.senlingspace.common.config.SenlingSpaceConfig;
import com.senlingspace.common.utils.file.FileUploadUtils;
import com.senlingspace.framework.config.ServerConfig;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.senlingspace.common.core.domain.AjaxResult;
import com.senlingspace.common.utils.StringUtils;

/**
 * 通用请求处理
 *
 * @author senlingspace
 */
@RestController
@RequestMapping("/common")
public class CommonController {
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private FileStorageService fileStorageService;

    private static final String FILE_DELIMETER = ",";


    /**
     * 通用上传请求（单个）
     *
     * @param file
     * @return {@link AjaxResult }
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        try {
            // 上传文件路径
            String filePath;
            String filename = file.getOriginalFilename();
            if (StringUtils.isNotEmpty(filename) && filename.endsWith(".zip")) {
                filePath = SenlingSpaceConfig.getPackageUploadPath();
            } else {
                filePath = SenlingSpaceConfig.getUploadPath();
            }
            log.info("filePath: {}", filePath);

            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            log.info("fileName: {}", fileName);

            String url = serverConfig.getUrl() + fileName;

            JSONObject response = JSONObject.of("url", url,
                    "fileName", fileName);
            return AjaxResult.success(response);
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return AjaxResult.error(e.getMessage());
        }
    }


    /**
     * OSS上传文件
     *
     * @param file
     * @return
     */
    // @PostMapping("/upload")
    // public AjaxResult uploadFileToOss(MultipartFile file) {
    //     if (file.isEmpty()) {
    //         return AjaxResult.error("文件不能为空！");
    //     }
    //
    //     String filename = file.getOriginalFilename();
    //
    //     if (StringUtils.isBlank(filename)) {
    //         return AjaxResult.error("文件名不能为空！");
    //     }
    //
    //     if (StrUtil.isBlank(FileUtil.extName(filename))) {
    //         return AjaxResult.error("文件格式不正确！");
    //     }
    //
    //     String folder = new SimpleDateFormat("yyMMdd").format(new Date());
    //     String path = filename.endsWith(".apk") ? "app/" + folder + "/" : "res/" + folder + "/";
    //     String saveFilename = filename.endsWith(".apk") ? filename : "";
    //
    //     FileInfo fileInfo = fileStorageService.of(file)
    //             .setPath(path)
    //             .setSaveFilename(saveFilename)
    //             .upload();
    //
    //     log.info("文件上传，入参：{}，返回：{}", filename, JSON.toJSONString(fileInfo));
    //
    //     JSONObject response = JSONObject.of("url", fileInfo.getUrl(),
    //             "fileName", fileInfo.getFilename());
    //     return AjaxResult.success(response);
    // }

    /**
     * OSS文件下载
     *
     * @param url
     * @return
     */
    @GetMapping(path = "/download")
    public ResponseEntity<ByteArrayResource> download(@RequestParam String url) {
        log.info("文件下载，入参：{}", url);
        Stopwatch stopwatch = Stopwatch.createStarted();

        if (StringUtils.isBlank(url)) {
            log.info("URL 不能为空！");
            return ResponseEntity.badRequest().body(null);
        }

        FileInfo fileInfo = fileStorageService.getFileInfoByUrl(url);
        if (fileInfo == null) {
            log.info("文件不存在！");
            return ResponseEntity.notFound().build();
        }

        try {
            byte[] bytes = fileStorageService.download(url).bytes();
            HttpHeaders headers = createHeaders(fileInfo.getOriginalFilename());

            log.info("文件 {} 下载共耗时：{}", url, stopwatch.stop());
            return ResponseEntity.ok()
                    .headers(headers)
                    .contentLength(bytes.length)
                    .body(new ByteArrayResource(bytes));
        } catch (Exception e) {
            log.error("系统异常，下载失败：", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    private HttpHeaders createHeaders(String originalFilename) throws UnsupportedEncodingException {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", URLEncoder.encode(originalFilename, StandardCharsets.UTF_8.name()));
        return headers;
    }

}
